﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Travel.CommonUtil.Snowflake;
using Travel.Data;
using Travel.Data.Dtos;
using Travel.Data.Dtos.TravelBusiness;
using Travel.Data.Entity;
using Travel.Data.Enums;
using Travel.Data.Inputs;

namespace Travel.Service.TravelBusiness.Impl
{
    /// <summary>
    /// 旅游相关服务-实现类
    /// </summary>
    public class TraveIService : ServiceBase, ITraveIService
    {
        private readonly HappyTravelContext _context;
        private readonly IMapper _mapper;
        private readonly IdWorker _idWorker;
        public TraveIService(HappyTravelContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
            _idWorker = SnowflakeUtil.CreateIdWorker();
        }
        /// <summary>
        /// 查看详情
        /// </summary>
        /// <param name="travelId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<TravelDetailDto>> GetDetail(long travelId)
        {
            var travel = await _context.TabTravels.AsNoTracking().Include(c => c.Category).FirstOrDefaultAsync(c => !c.Deleted && c.Id == travelId);
            if (travel == null)
            {
                return Results<TravelDetailDto>.FailResult("未找到记录");
            }
            if (travel.AuditStatus != Data.Enums.AuditStatusEnum.Pass)
            {
                return Results<TravelDetailDto>.FailResult("当前景点未上线");

            }
            if (!travel.IsLaunched)
            {
                return Results<TravelDetailDto>.FailResult("当前旅游景点未上架");
            }
            if (travel.EndTime < DateTime.Now)
            {
                return Results<TravelDetailDto>.FailResult("活动时间已过");
            }
            TravelDetailDto travelDetailDto = _mapper.Map<TravelDetailDto>(travel);
            List<TabTravelImg> imgList = _context.TabTravelImgs.AsNoTracking().Where(c => c.TravelId == travelId).ToList();
            travelDetailDto.ImageList = _mapper.Map<List<TravelImageDto>>(imgList);
            return Results<TravelDetailDto>.DataResult(travelDetailDto);
        }
        /// <summary>
        /// 查看游客列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<QueryTravelUserDto>> QueryTravelUserList(TravelUserQueryInput input)
        {
            QueryTravelUserDto result = new QueryTravelUserDto();
            var userIdList = TravelContext.TabOrders.AsNoTracking().Where(c => !c.Deleted && c.TravelId == input.TravelId).Select(c=>c.CreatedUserId);
            if (!userIdList.Any())
            {
                return Results<QueryTravelUserDto>.FailResult("没有下单用户");
            }
            var details = TravelContext.TabOrderDetails.AsNoTracking().Where(c=> userIdList.Contains(c.Id));
            // 查询亲友列表
            result.UserList.AddRange(details.Select(c => new TravelUserDto
            {
                Username = "亲友",
                Nickname = c.FriendName,
                Mobile = c.FriendMobile,
                Email = string.Empty,
            }));
            //下单人信息
            var tabUsers = TravelContext.TabUsers.AsNoTracking().Where(c=>!c.Deleted && userIdList.Contains(c.Id));
            result.UserList.AddRange(ObjectMapper.Map<List<TravelUserDto>>(tabUsers));
            //领队信息
           var tabTravelLeaders = TravelContext.TabTravelLeaders.AsNoTracking().Where(c => !c.Deleted && c.TravelId == input.TravelId);
            if (tabTravelLeaders.Any())
            {
                result.LeaderList.AddRange(ObjectMapper.Map<List<LeaderUserDto>>(tabTravelLeaders));
            }
            return Results<QueryTravelUserDto>.DataResult(result);
        }

        /// <summary>
        /// 设置领队
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<int>> SetTravelLeader(SetTravelLeaderInput input)
        {
            var oleList = TravelContext.TabTravelLeaders.Where(c => !c.Deleted && c.TravelId == input.TravelId);
            if (!oleList.Any())
            {
                await oleList.ForEachAsync(c =>
                {
                    c.Deleted = true;
                    c.UpdatedUserId = LoginUserId;
                });
            }
            var tabUsers = TravelContext.TabUsers.Where(c => !c.Deleted && input.UserIdList.Contains(c.Id));
            foreach (var item in tabUsers)
            {
                TabTravelLeader tabTravel = new TabTravelLeader()
                {

                    Id = SnowIdWorker.NextId(),
                    CreatedUserId = LoginUserId,
                    LeaderMobile = item.Mobile,
                    LeaderNickname = item.Nickname,
                    TravelId = input.TravelId,
                    UpdatedUserId = LoginUserId,
                    LeaderUserId = item.Id,
                };
                TravelContext.TabTravelLeaders.Add(tabTravel);
            }
            return Results<int>.DataResult(await _context.SaveChangesAsync());
        }

        /// <summary>
        /// 删除旅游景点
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="loginUserId"></param>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<Results<int>> TracelDelete(long roleId, params long[] idList)
        {
            if (!idList.Any())
            {
                return Results<int>.FailResult("必须选中一条记录");
            }
            var list = _context.TabTravels.Where(c => !c.Deleted && idList.Contains(c.Id));
            if (list.Any())
            {
                return Results<int>.FailResult("记录不存在");
            }
            foreach (var item in list)
            {
                if (item.IsLaunched)
                {
                    return Results<int>.FailResult("存在未下架的商品");
                }
                if ((RoleEnum)roleId == RoleEnum.Seller && item.CreatedUserId != LoginUserId)
                {
                    return Results<int>.FailResult("商家只能删除自家商品");
                }
                item.Deleted = true;
                var imgList = _context.TabTravelImgs.Where(c => c.TravelId == item.Id);
                foreach (var img in imgList)
                {
                    img.Deleted = true;
                }
            }
            return Results<int>.DataResult(await _context.SaveChangesAsync());
        }

        /// <summary>
        /// 旅游景点添加或者修改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<int>> TravelAddOrUpdate(TravelAddOrUpdateInput input)
        {
            //验重（只验重当前的商家）
            var count = _context.TabTravels.AsNoTracking().Count(c => !c.Deleted && c.TravelName == input.TravelName && c.Id != input.Id && c.CreatedUserId == input.LoginUserId);
            if (count > 0)
            {
                return Results<int>.FailResult("旅游路线已存在");
            }
            var transaction = _context.Database.BeginTransaction();
            try
            {
                TabTravel tabTravel;
                if (input.Id > 0)
                {
                    tabTravel = await _context.TabTravels.FirstOrDefaultAsync(c => c.Id == input.Id);
                    _mapper.Map(input, tabTravel);
                }
                else
                {
                    tabTravel = _mapper.Map<TabTravel>(input);
                    tabTravel.Id = _idWorker.NextId();
                    tabTravel.AuditStatus = Data.Enums.AuditStatusEnum.UnAudit;
                    tabTravel.IsLaunched = false;
                    tabTravel.FavoriteCount = 0;
                    await _context.TabTravels.AddAsync(tabTravel);
                }
                if (input.ImageList.Any())
                {
                    var imgList = _context.TabTravelImgs.Where(c => c.Id == input.Id);
                    if (imgList.Any())
                    {
                        //先清理后添加
                        _context.TabTravelImgs.RemoveRange(imgList);
                    }
                    var newImageList = _mapper.Map<List<TabTravelImg>>(input.ImageList);
                    newImageList.ForEach(c =>
                    {
                        c.Id = _idWorker.NextId();
                        c.CreatedUserId = input.LoginUserId;
                        c.UpdatedUserId = input.LoginUserId;
                        c.TravelId = tabTravel.Id;
                        _context.TabTravelImgs.Add(c);
                    });
                }
                int row = await _context.SaveChangesAsync();
                await transaction.CommitAsync();
                return Results<int>.DataResult(row);
            }
            catch (Exception)
            {
                await transaction.CommitAsync();
                return Results<int>.FailResult();
            }
            finally { transaction.Dispose(); }
        }
        /// <summary>
        /// 旅游景点审批
        /// </summary>
        /// <param name="travelAuditInput"></param>
        /// <returns></returns>
        public async Task<Results<int>> TravelAudit(TravelAuditInput input)
        {
            var list = _context.TabTravels.Where(c => !c.Deleted && input.TravelIdList.Contains(c.Id) && c.AuditStatus == AuditStatusEnum.UnAudit);
            if (!list.Any())
            {
                return Results<int>.FailResult("请选择待审批的记录");
            }
            foreach (var item in list)
            {
                if (input.HasPass)
                {
                    item.IsLaunched = true;
                    item.AuditStatus = AuditStatusEnum.Pass;
                    item.LaunchedTime = DateTime.Now;
                }
                else
                {
                    item.AuditStatus = AuditStatusEnum.Refuse;
                }
                item.UpdatedUserId = input.LoginUserId;
            }

            return Results<int>.DataResult(await _context.SaveChangesAsync());
        }

        /// <summary>
        /// 旅游景点查询
        /// </summary>
        /// <param name="travelQueryInput"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Results<PageDto<TravelDto>>> TravelQuery(TravelQueryInput input)
        {
            var query = _context.TabTravels.AsNoTracking().Include(c => c.Category).Where(c => !c.Deleted);
            if (input.CategoryId > 0)
            {
                query = query.Where(c => c.CategoryId == input.CategoryId);
            }
            if (input.StartLaunchedTime.HasValue && !input.StartLaunchedTime.Value.ToString().StartsWith("1991"))
            {
                query = query.Where(c => c.LaunchedTime >= input.StartLaunchedTime);
            }
            if (input.EndLaunchedTime.HasValue && !input.EndLaunchedTime.Value.ToString().StartsWith("1991"))
            {
                query = query.Where(c => c.LaunchedTime <= input.EndLaunchedTime);
            }
            if (!string.IsNullOrWhiteSpace(input.TravelName))
            {
                query = query.Where(c => c.TravelName == input.TravelName);
            }
            if (input.StartPrice > 0 && input.EndPrice > 0)
            {
                query = query.Where(c => c.Price >= input.StartPrice && c.Price <= input.EndPrice);
            }
            if (input.IsLaunched.HasValue)
            {
                query = query.Where(c => c.IsLaunched == input.IsLaunched);
            }
            if (input.AuditStatus.HasValue)
            {
                query = query.Where(c => c.AuditStatus == input.AuditStatus);
            }
            if (input.IsUserSearch)
            {
                query = query.Where(c => c.StartTime >= DateTime.Now);
            }
            if (input.CreatedUserId > 0)
            {
                query = query.Where(c => c.CreatedUserId == input.CreatedUserId);
            }
            PageDto<TravelDto> page = new PageDto<TravelDto>()
            {

                Total = query.Count(),
            };
            List<TabTravel> list = query.OrderBy(c => c.StartTime).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList();


            page.Data = _mapper.Map<List<TravelDto>>(list);


            //查询用户
            var createUserIdList = list.Select(c => c.CreatedUserId);
            Dictionary<long, TabUser> dict = _context.TabUsers.Where(c => createUserIdList.Contains(c.Id)).ToDictionary(c => c.Id);
            page.Data.ForEach(c =>
            {
                c.SellerUserName = dict[c.CreatedUserId].Nickname;
            });
            return Results<PageDto<TravelDto>>.DataResult(page);
        }
        /// <summary>
        /// 上架或者下架旅游景点
        /// </summary>
        /// <param name="travelShekverOrUnShelveInput"></param>
        /// <returns></returns>
        public async Task<Results<int>> TravelShekverOrUnShelve(TravelShekverOrUnShelveInput input)
        {
            var list = _context.TabTravels.Where(c => !c.Deleted && input.TravelIdList.Contains(c.Id) && c.IsLaunched != input.HasShelve);
            if (!list.Any())
            {
                return Results<int>.FailResult($"您选中的数据未存在{(input.HasShelve ? "上架" : "下架")}");
            }
            foreach (var item in list)
            {
                item.IsLaunched = input.HasShelve;
                item.UpdatedUserId = input.LoginUserId;
                if (input.HasShelve)
                {
                    item.LaunchedTime = DateTime.Now;
                }
                else
                {
                    item.LaunchedTime = null;
                }
            }
            return Results<int>.DataResult(await _context.SaveChangesAsync());
        }
    }
}
